import 'dart:async';

import 'package:alipay_kit/alipay_kit_platform_interface.dart';
import 'package:flutter/material.dart';

class EMIAlipayPurchaseManger {
  factory EMIAlipayPurchaseManger() => _instance;
  static final EMIAlipayPurchaseManger _instance =
      EMIAlipayPurchaseManger._internal();

  // static const bool _ALIPAYUSE_RSA2 = true;
  // static const String _ALIPAY_APPID = 'your alipay appId'; // 支付/登录
  // static const String _ALIPAY_PID = 'your alipay pid'; // 登录
  // static const String _ALIPAY_TARGETID = 'your alipay targetId'; // 登录
  // static const String _ALIPAY_PRIVATEKEY =
  //     'your alipay rsa private key(pkcs1/pkcs8)';

  late final StreamSubscription<AlipayResp> paySubs;
  late final StreamSubscription<AlipayResp> authSubs;

  Function(bool)? payCallback;

  EMIAlipayPurchaseManger._internal() {
    paySubs = AlipayKitPlatform.instance.payResp().listen(_listenPay);
    authSubs = AlipayKitPlatform.instance.authResp().listen(_listenAuth);
  }

  void _listenPay(AlipayResp resp) {
    final String content = '支付1 pay: ${resp.resultStatus} - ${resp.result}';
    if (payCallback != null) payCallback!(resp.resultStatus == 9000);
    debugPrint(content);
  }

  void _listenAuth(AlipayResp resp) {
    final String content = '支付2 pay: ${resp.resultStatus} - ${resp.result}';
    if (payCallback != null) payCallback!(resp.resultStatus == 9000);
    debugPrint(content);
  }

  didPay(String orderInfo, Function(bool) callback) {
    payCallback = callback;
    AlipayKitPlatform.instance.pay(orderInfo: orderInfo);
  }
}
